package cn.wolfcode.user.servlet;

import cn.wolfcode.user.entity.User;
import cn.wolfcode.user.service.UserService;
import cn.wolfcode.user.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 李新雨的项目86176
 * @version 1.0
 * @date 2024-10-30 20:14
 */
@WebServlet("/replaceImg")
@MultipartConfig(maxFileSize = 5000000)
public class ReplaceImgServlet extends HttpServlet {
    private final UserService userService=new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        //// TODO: 2024/10/30  获取图片
        Part headImg = req.getPart("headImg");
        System.out.println(headImg);
        if(!(headImg.getContentType().startsWith("image/"))){
            req.setAttribute("imgMsg","请上传图片，重新上传");
            req.getRequestDispatcher("/replaceImg.jsp").forward(req,resp);
            return;
        }
        //获取文件的完整名称
        String realName = headImg.getSubmittedFileName();
        String suffix = realName.substring(realName.indexOf('.'));
        String newName=  UUID.randomUUID().toString()+ suffix;
        //// TODO: 2024/10/30  ？？？
        //D:\javaCode\Three-layer-architecture-project\out\artifacts
        // \Three_layer_architecture_project_war_exploded
        // \c9b01105-e281-4947-ae07-62b4d155749d.jpg
        /**通过请求对象获取文本域对象，
         * 调用方法获取文件上传的真实地址。
         * 从服务器中上传的图片*/
        /**
         * 由于通过服务器完成文件上传，而指定的位置也是通过服务器创建。
         * 因此需要在服务器作用域中获取上传的位置
         */
        String path=req.getServletContext().getRealPath("image/")+newName;
//        System.out.println(path);
        //
        Object user_in_session = req.getSession().getAttribute("USER_IN_SESSION");
        User user=(User) user_in_session;
        if(user!=null) {
            //// TODO: 2024/10/30  将服务器中上传的地址设置给指定的字段
            //??????????????????????????????????????????????//
            /**
             * 相对路径
             */
            user.setHeadImg("image/"+newName);
            userService.editHeadImg(user);
            //// TODO: 2024/10/30
            /**
             *
             *输出流对象
             *
             * 将文件上传，将图片写到真实路径下面
             *
             */
            headImg.write(path);
            resp.sendRedirect("/book");
//        }

        }else {
            resp.sendRedirect("/login.jsp");
        }
    }
}
